package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.system.domain.ActCategory;
import com.ruoyi.system.domain.ActTitle;
import com.ruoyi.system.domain.Game;
import com.ruoyi.system.dto.ResultDto;
import com.ruoyi.system.service.*;
import com.ruoyi.system.vo.ActPrizeVO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.ActPrize;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 获奖名单Controller
 *
 * @author xuyk
 * @date 2022-06-22
 */
@Controller
@RequestMapping("/system/prize")
public class ActPrizeController extends BaseController
{
    private String prefix = "system/prize";

    @Autowired
    private IActPrizeService actPrizeService;

    @Autowired
    private IActService actService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private IActTitleService actTitleService;

    @Autowired
    private IGameService gameService;

    @Autowired
    private IActCategoryService actCategoryService;

    @RequiresPermissions("system:prize:view")
    @GetMapping()
    public String prize(ModelMap mmap)
    {
        boolean allSelectPerm = false;
        SysDept dept = sysDeptService.selectDeptById(getSysUser().getDeptId());
        if(dept == null){
            return null;
        }
        if(dept.getAncestors().startsWith("0,100") || dept.getDeptId().intValue() == 100){
            allSelectPerm = true;
        }
        List<Game> games = gameService.selectDefault();
        mmap.put("games",games);
        mmap.put("allSelectPerm",allSelectPerm);
        return prefix + "/prize";
    }

    /**
     * 查询获奖名单列表
     */
    @RequiresPermissions("system:prize:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ActPrize actPrize)
    {
        SysDept dept = sysDeptService.selectDeptById(getSysUser().getDeptId());
        if(dept == null){
            return null;
        }
        actPrize.setCurUser(getSysUser().getLoginName());
        if(dept.getAncestors().startsWith("0,100") || dept.getDeptId().intValue() == 100){
            actPrize.setAllSelectPerm(true);
        }
        //查询用户所在的学院
        if(actPrize.isAllSelectPerm() == false){
            SysDept curUserFaculty = sysDeptService.getUserFaculty(getSysUser());
            if(curUserFaculty != null){
                actPrize.setCurUserFacultyId(curUserFaculty.getDeptId());
            }else{
                return null;
            }
        }
        startPage();
        List<ActPrize> list = actPrizeService.selectActPrizeList(actPrize);
        return getDataTable(list);
    }

    /**
     * 导出获奖名单列表
     */
    @RequiresPermissions("system:prize:export")
    @Log(title = "获奖名单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ActPrize actPrize)
    {
        SysDept dept = sysDeptService.selectDeptById(getSysUser().getDeptId());
        if(dept == null){
            return null;
        }
        actPrize.setCurUser(getSysUser().getLoginName());
        if(dept.getAncestors().startsWith("0,100") || dept.getDeptId().intValue() == 100){
            actPrize.setAllSelectPerm(true);
        }
        //查询用户所在的学院
        if(actPrize.isAllSelectPerm() == false){
            SysDept curUserFaculty = sysDeptService.getUserFaculty(getSysUser());
            if(curUserFaculty != null){
                actPrize.setCurUserFacultyId(curUserFaculty.getDeptId());
            }else{
                return null;
            }
        }
        startPage();
        List<ActPrize> list = actPrizeService.selectActPrizeList(actPrize);
        ExcelUtil<ActPrize> util = new ExcelUtil<ActPrize>(ActPrize.class);
        return util.exportExcel(list, "获奖名单数据");
    }

    /**
     * 新增获奖名单
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        mmap.put("curDeptId",getSysUser().getDeptId());
        List<Game> games = gameService.selectDefault();
        if(games !=null && games.size() >0){
            Long gameId = games.get(0).getId();
            List<ActCategory> categories = actCategoryService.findWholeTree();
            ActCategory actCategory = null;
            if(categories != null && categories.size()>0){
                for(ActCategory item: categories){
                    if(item.hasChildren()){
                        actCategory = item.getChildren().get(0);
                    }else{
                        actCategory = item;
                    }
                    break;
                }
                Long categoryId = actCategory.getId();
                List<ActTitle> actTitles = actTitleService.selectByGameIdAndCategoryId(gameId,categoryId);
                mmap.put("categoryTree",categories);
                mmap.put("actTitles",actTitles);
                mmap.put("games",games);
                return prefix + "/add";
            }
        }

        mmap.put("actTitles",null);
        mmap.put("games",null);
        mmap.put("categoryTree",null);
        return prefix + "/add";
    }

    /**
     * 新增保存获奖名单
     */
    @RequiresPermissions("system:prize:add")
    @Log(title = "获奖名单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ActPrize actPrize)
    {
        //校验actNo是否存在
        boolean isExistActNo = actPrizeService.isExistActNo(actPrize.getActNo(),actPrize.getGameId(),null);
        if(isExistActNo){
            return AjaxResult.error("参赛编号的作品已经存在，请重新输入！");
        }
        // 校验院系是否正确
        SysDept sysDept = sysDeptService.selectDeptById(actPrize.getFacultyId());
        if(sysDept == null || sysDept.getAncestors().equals("0,101") || sysDept.getAncestors().startsWith("0,101") == false
        ){
            return AjaxResult.error("请选择正确的院系！");
        }
        actPrize.setCreateBy(getLoginName());
        return toAjax(actPrizeService.insertActPrize(actPrize));
    }

    /**
     * 修改获奖名单
     */
    @RequiresPermissions("system:prize:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        ActPrize actPrize = actPrizeService.selectActPrizeById(id);
        mmap.put("actPrize", actPrize);

        mmap.put("curDeptId",getSysUser().getDeptId());
        List<ActCategory> categories = actCategoryService.findWholeTree();
        if(actPrize != null){
            String schoolName = actPrize.getSchool();
            String beginChar = schoolName.substring(0,1);
            if("0123456789".indexOf(beginChar) > -1){
                String begin = schoolName.substring(0,6);
                begin = begin.replaceAll("[0-9|-]","");
                schoolName = begin + schoolName.substring(6);
            }
            actPrize.setSchool(schoolName);

            Long gameId = actPrize.getGameId();
            Long categoryId = actPrize.getCategoryId();
            if(gameId!= null && categoryId != null){
                List<ActTitle> actTitles = actTitleService.selectByGameIdAndCategoryId(gameId,categoryId);
                mmap.put("titles",actTitles);
            }else{
                mmap.put("titles",null);
            }
        }else{
            mmap.put("titles",null);
        }
        List<String> prizeLevels = new ArrayList<>();
        prizeLevels.add("一等奖");
        prizeLevels.add("二等奖");
        prizeLevels.add("三等奖");
        mmap.put("prizeLevels",prizeLevels);

        List<String> sendAudits = new ArrayList<>();
        sendAudits.add("是");
        sendAudits.add("否");
        mmap.put("sendAudits",sendAudits);
        mmap.put("categoryTree",categories);

        return prefix + "/edit";
    }

    /**
     * 修改保存获奖名单
     */
    @RequiresPermissions("system:prize:edit")
    @Log(title = "获奖名单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ActPrize actPrize)
    {
        actPrize.setUpdateBy(getLoginName());
        return toAjax(actPrizeService.updateActPrize(actPrize));
    }

    /**
     * 删除获奖名单
     */
    @RequiresPermissions("system:prize:remove")
    @Log(title = "获奖名单", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(actPrizeService.deleteActPrizeByIds(ids));
    }


    @Log(title = "获奖名单", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:prize:import")
    @PostMapping("/import")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, Long gameId) throws Exception
    {
        if(gameId == null || gameId <= 0){
            return AjaxResult.error("请选择大赛名称");
        }
        ExcelUtil<ActPrizeVO> util = new ExcelUtil<ActPrizeVO>(ActPrizeVO.class);
        List<ActPrizeVO> actPrizeVOS = util.importExcel(file.getInputStream());
        if(actPrizeVOS == null || actPrizeVOS.size() == 0){
            return AjaxResult.error("导入的数据为空");
        }

        ResultDto resultDto = actPrizeService.importActPrizeData(actPrizeVOS,gameId,getSysUser());
        if(resultDto.isSuccess()){
            String message = "导入成功";
            return AjaxResult.success(message);
        }else{
            return AjaxResult.error(resultDto.getMessage());
        }
    }


}
